<template>
  <div class="wrapper" :style="{ backgroundImage: 'url(' + bg + ')'}">
    <div class="form-wrapper mid">
      <div class="header">
        <div class="title">
          <span>TxBlog 后台登录</span>
        </div>
      </div>
      <div class="content">
        <Form ref="formInline" :model="formInline" :rules="ruleInline">
          <FormItem prop="username">
            <Input type="text" v-model="formInline.username" placeholder="用户名" :maxlength="10">
              <Icon type="ios-person-outline" slot="prepend"></Icon>
            </Input>
          </FormItem>
          <FormItem prop="password">
            <Input type="password" @on-enter="handleSubmit('formInline')" v-model="formInline.password" placeholder="密码" :maxlength="16">
              <Icon type="ios-lock-outline" slot="prepend"></Icon>
            </Input>
          </FormItem>
          <FormItem>
            <Button type="primary" size="large" long @click="handleSubmit('formInline')">登录</Button>
          </FormItem>
        </Form>
      </div>
    </div>
  </div>
</template>

<style scoped lang="sass">
  @import "../styles/login.sass"
</style>

<script>
import { Button, Form, FormItem, Input, Icon } from 'view-design'
import tk from '@/utils/token'
import Qs from 'qs'

export default {
  data () {
    return {
      bg: require('@/assets/bg.jpg'),
      formInline: {
        username: '',
        password: ''
      },
      ruleInline: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            type: 'string',
            min: 6,
            message: '密码必须最少6位数',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  components: {
    Button,
    Form,
    FormItem,
    Input,
    Icon
  },
  methods: {
    handleSubmit (name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          this.doLogin({
            username: this.formInline.username,
            password: this.formInline.password
          })
        }
      })
    },
    doLogin (data) {
      this.$request.post('/api/login', Qs.stringify(data), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).then(
        (resp) => {
          // const { expiredAt, createdAt, token } = resp.result
          console.log('success', resp)
          tk.set(resp.data, 7) // (expiredAt - createdAt) / 86400000)
          this.$router.replace('/')
        },
        (error) => {
          this.formInline = {
            username: '',
            password: ''
          }
          this.$Message.error(error.message)
        }
      )
    }
  }
}
</script>

<style lang="sass" scoped>
  @import "../styles/login.sass"
</style>
